<template>
	<coreshop-page title="个人资料" mode="left">
		<view class="layout-userinfo-box">
			<view class="progress-box">
				<view class="title">完善度</view>
				<uv-line-progress :percentage="state.percentage" inactiveColor="#fff"
					activeColor="#D33123"></uv-line-progress>
			</view>
			<view class="user-box">
				<view class="title">基本资料</view>
				<view class="msg-box">
					<view class="item-box">
						<view class="lab">头像</view>
						<view class="val">
							<!-- #ifdef MP-WEIXIN  -->
							<button class="avatar-botton" open-type="chooseAvatar" @chooseavatar="getChooseavatar">
								<image v-if="state.avatar" class="img" :src="state.avatar"></image>
								<image v-else class="img" src="/static/images/member/upload.png"></image>
							</button>
							<!-- #endif --> 
							<!-- #ifndef MP-WEIXIN -->
							<view class="upload-box" @click="handleUploadAvatar">
								<image v-if="state.avatar" class="img" :src="state.avatar"></image>
								<image v-else class="img" src="/static/images/member/upload.png"></image>
							</view>
							<!-- #endif -->
						</view>
					</view>
					<view class="item-box center">
						<view class="lab">昵称</view>
						<view class="val">
							<input type="nickname" placeholder="请输入昵称" border="none" :value="state.nickname" @change="hanldeChangeNickName"></input>
						</view>
					</view>
					<view class="item-box center">
						<view class="lab">性别</view>
						<view class="val">
							<uv-radio-group v-model="state.sex" activeColor="#D33123">
								<uv-radio :customStyle="{ 'margin-right': '40rpx' }"
									v-for="(item, index) in state.radiolist" :key="index" :label="item.name"
									:name="item.name">
								</uv-radio>
							</uv-radio-group>
						</view>
					</view>
					<view class="item-box center">
						<view class="lab">生日</view>
						<view class="val" @click="handleOpenDatetime">
							<uv-input placeholder="请输入生日" :value="state.birthday" border="none" readonly></uv-input>
						</view>
					</view>
				</view>
			</view>

			<view class="save-box" @click="handleSubmit">保存</view>

			<uv-datetime-picker ref="datetimePicker" :minDate="-639100800000" :maxDate="new Date().getTime()"
				v-model="state.birthdayTemporary" :formatter="formatter" mode="date"
				@confirm="confirm"></uv-datetime-picker>
		</view>
	</coreshop-page>
</template>
<script setup lang="ts">
	import { reactive, ref } from 'vue';
	import { timeFormat } from '@/core/utils';
	import { onReady, onLoad } from '@dcloudio/uni-app';
	import type { Response, UserInfoType } from '@/core/models';
	import { queryUserInfo, queryUploadImages, queryChangeAvatar, queryEditInfo } from '@/core/api';
	import { SexEnum, RouteSwitchTabEnum } from '@/core/enum';
	import { handleShowToast, handleRouteSwitchTab } from '@/core/utils';

	const datetimePicker = ref();

	const state = reactive<{
		nickname : string;
		radiolist : Array<{ [key : string] : any }>;
		sex : string;
		birthdayTemporary : number;
		birthday : string;
		avatar : string;
		userInfo : UserInfoType,
		submitStatus : boolean;
		percentage : number
	}>({
		userInfo: {},
		avatar: "",
		nickname: "",
		sex: "",
		birthdayTemporary: null,
		birthday: "",
		submitStatus: true,
		radiolist: [{
			name: '男',
			val: SexEnum.male,
		}, {
			name: '女',
			val: SexEnum.female,
		}, {
			name: '保密',
			val: SexEnum.secrecy,
		}],
		percentage: 0,
	})

	onLoad(() => {
		getUserInfo();
	});

	onReady(() => {
		datetimePicker?.value.setFormatter(formatter)
	});

	/** 获取头像*/
	const getChooseavatar = (res : any) => {
		handleUploadImages(res.detail.avatarUrl);
	}

	/** 上传 */
	const handleUploadAvatar = () => {
		uni.chooseImage({
			count: 1,
			success(res : any) {
				handleUploadImages(res.tempFilePaths[0]);
			}
		})
	}

	/** 请求上传头像 */
	const handleUploadImages = async (url : string) => {
		const img : Response<any> = await queryUploadImages(url);
		if (img.status) {
			state.avatar = img?.data?.src;
			const changeAvatar : Response<any> = await queryChangeAvatar({ id: img?.data?.src });
			if (changeAvatar.status) {
				handleShowToast('上传成功', 'success');
			} else {
				handleShowToast('上传失败');
			}
		} else {
			handleShowToast('上传失败');
		}
	}
	
	/** 修改昵称 */
	const hanldeChangeNickName= (e:any)=>{
		state.nickname = e.detail?.value?.trim();
	}
	
	/** 获取用户信息 */
	const getUserInfo = async () => {
		const userInfo : Response<UserInfoType> = await queryUserInfo();
		state.userInfo = userInfo?.data;
		if (userInfo?.data?.birthday) {
			state.percentage += 25;
			state.birthdayTemporary =new Date(userInfo.data.birthday).getTime();
			state.birthday = timeFormat(userInfo?.data?.birthday, 'yyyy-mm-dd');
		}
		if (userInfo?.data?.nickName) {
			state.percentage += 25;
			state.nickname = userInfo?.data?.nickName?.trim();
		}
		if (userInfo?.data?.avatarImage) {
			state.percentage += 25;
			state.avatar = userInfo?.data?.avatarImage;
		}
		if (userInfo?.data?.mobile) {
			state.percentage += 25;
		}
		if (userInfo?.data?.sex === SexEnum.male) {
			state.sex = '男'
		} else if (userInfo?.data?.sex === SexEnum.female) {
			state.sex = '女'
		} else if (userInfo?.data?.sex === SexEnum.secrecy) {
			state.sex = '保密'
		}
	}

	const handleOpenDatetime = () => {
		datetimePicker.value.open();
	}

	const formatter = (type : string, value : number) => {
		if (type === 'year') {
			return `${value}年`
		}
		if (type === 'month') {
			return `${value}月`
		}
		if (type === 'day') {
			return `${value}日`
		}
		return value
	}

	const confirm = (e : any) => {
		state.birthdayTemporary = e.value;
		state.birthday = timeFormat(e.value, 'yyyy-mm-dd');
	}

	/** 提交 */
	const handleSubmit = async () => {
		if (!state.submitStatus) {
			return;
		}
		if (!state.nickname) {
			handleShowToast('请输入昵称'); return;
		} 
		if (!state.sex) {
			handleShowToast('请选择性别'); return;
		}
		if (!state.birthday) {
			handleShowToast('请选择生日'); return;
		}
		state.submitStatus = false;
		const info : Response<any> = await queryEditInfo({
			sex: (state.radiolist.find((item : any) => item.name == state.sex))?.val,
			birthday: state.birthday,
			nickname: state.nickname
		});
		if (info.status) {
			state.submitStatus = true;
			handleShowToast(info.msg, 'success', () => {
				setTimeout(() => {
					handleRouteSwitchTab(RouteSwitchTabEnum.member)
				}, 1500)
			});
		} else {
			state.submitStatus = true;
			handleShowToast(info.msg);
		}
	}
</script>
<style lang="scss" scoped>
	@import './userInfo.scss';
</style>